package com.labichaoka.chaoka.ui.baseinfo.edu;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.BaseActivity;
import com.labichaoka.chaoka.entity.IDCardRequest;
import com.labichaoka.chaoka.utils.ImageUtil;
import com.labichaoka.chaoka.utils.PhotoUtils;
import com.labichaoka.chaoka.utils.RandomUntil;
import com.labichaoka.chaoka.utils.ThreadPoolManager;
import com.labichaoka.chaoka.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class EducationImgUploadActivity extends BaseActivity implements EducationImgUploadView {

    @BindView(R.id.edu_img)
    ImageView frontImg;
    @BindView(R.id.front_txt)
    TextView frontTxt;
    @BindView(R.id.front_close)
    TextView frontClose;
    @BindView(R.id.hand_img)
    ImageView backImg;
    @BindView(R.id.back_txt)
    TextView backTxt;
    @BindView(R.id.back_close)
    TextView backClose;
    @BindView(R.id.commit)
    Button commit;

    private Dialog dialog;
    private int front = 0;
    private int back = 1;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
    private Uri imageUri;
    private final static int PHOTO_REQUEST = 100;
    private final static int PHOTO_PICK = 101;
    private boolean isFront = true; //标识是上传正面还是反面，true为正面
    private Uri resultUri;
    private Bitmap tmpBitmap;
    private String front_name;
    private String back_name;
    private String front_uri_str;
    private String back_uri_str;
    private List<IDCardRequest.IDCard> list;
    private Map<String,IDCardRequest.IDCard> map;

    private EducationImgUploadPresenter presenter;

    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (isFront) {
                    //正面
                    frontImg.setImageBitmap(tmpBitmap);
                    hideProgress();
                    frontClose.setVisibility(View.VISIBLE);
                    frontTxt.setVisibility(View.GONE);
                    frontImg.setEnabled(false);

                } else {
                    backImg.setImageBitmap(tmpBitmap);
                    hideProgress();
                    backClose.setVisibility(View.VISIBLE);
                    backTxt.setVisibility(View.GONE);
                    backImg.setEnabled(false);
                }

            }else if(msg.what==2){
                if(map!=null&&map.size()==1){
                    commit.setEnabled(true);
                }else{
                    commit.setEnabled(false);
                }
            }

        }
    };


    @Override
    protected int initLayoutId() {
        return R.layout.activity_identify_upload;
    }

    @Override
    protected void initView() {
        frontClose.setTypeface(iconfont);
        backClose.setTypeface(iconfont);
    }

    @Override
    protected void initData() {
        dialog = new Dialog(mContext, R.style.Translucent_NoTitle);
        map=new HashMap<>();
        presenter=new EducationImgUploadPresenterImpl(new EducationImgUploadInteractorImpl(),this);
    }

    @OnClick({R.id.commit,R.id.edu_img, R.id.hand_img,R.id.front_close,R.id.back_close})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.commit:
                list=new ArrayList<>();
                list.add(map.get("0"));
                list.add(map.get("0"));
                IDCardRequest request=new IDCardRequest();
                request.setFileBase64Arr(list);
                presenter.upload(request);

                break;
            case R.id.edu_img:
                isFront=true;
                showBottomDialog(front);
                break;
            case R.id.hand_img:
                isFront=false;
                showBottomDialog(back);
                break;
            case R.id.front_close:
                if (map!=null&&map.size()>0){
                    map.remove("0");
                }
                frontImg.setImageResource(R.mipmap.idcard1);
                frontClose.setVisibility(View.GONE);
                frontTxt.setVisibility(View.VISIBLE);
                frontImg.setEnabled(true);
                checkButtonState();
                break;
            case R.id.back_close:
                if (map!=null&&map.size()>0){
                    map.remove("1");
                }
                backImg.setImageResource(R.mipmap.idcard2);
                backClose.setVisibility(View.GONE);
                backTxt.setVisibility(View.VISIBLE);
                backImg.setEnabled(true);
                checkButtonState();
                break;
        }
    }

    public void showBottomDialog(int type) {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.upload_bottom_dialog, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.showdialog);
        TextView close_icon = (TextView) v.findViewById(R.id.close);
        TextView take_photo = (TextView) v.findViewById(R.id.take_photo);
        TextView selected_photo = (TextView) v.findViewById(R.id.selected_photo);
        ImageView img = (ImageView) v.findViewById(R.id.img_bg);

        if (type == 0) {
            img.setImageResource(R.mipmap.idchi);
        } else {
            img.setImageResource(R.mipmap.idchi);
        }

        close_icon.setTypeface(iconfont);
        close_icon.setOnClickListener((view) -> {
            dialog.dismiss();
        });

        //拍照
        take_photo.setOnClickListener((view) -> {
            dialog.dismiss();
            //获取拍照权限
            checkPermission(new CheckPermListener() {
                @Override
                public void Granted() {
                    imageUri = Uri.fromFile(fileUri);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        imageUri = FileProvider.getUriForFile(EducationImgUploadActivity.this, getPackageName() + ".path", fileUri);//通过FileProvider创建一个content类型的Uri

                    }
                    PhotoUtils.takePicture(EducationImgUploadActivity.this, imageUri, PHOTO_REQUEST);

                }

                @Override
                public void Denied() {

                }
            }, "请求获取拍照权限", Manifest.permission.CAMERA);
        });

        //相册上传
        selected_photo.setOnClickListener((view) -> {
            dialog.dismiss();
            //获取存储卡权限
            checkPermission(new CheckPermListener() {
                @Override
                public void Granted() {
                    PhotoUtils.openPic(EducationImgUploadActivity.this, PHOTO_PICK);

                }

                @Override
                public void Denied() {

                }
            }, "请求获取存储卡权限", Manifest.permission.READ_EXTERNAL_STORAGE);
        });

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(false);

        dialog.show();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void showProgress() {
        showLoadingProgress();
    }

    @Override
    public void hideProgress() {
        hideLoadingProgress();
    }

    @Override
    public void showMessage(String str) {
        ToastUtils.show(str);
    }

    @Override
    public void uploadSuccessed() {
        gotoActivity(mContext,QuoteResultActivity.class,null);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PHOTO_REQUEST) {
            //拍照
            resultUri=imageUri;
        } else if (requestCode == PHOTO_PICK) {
            resultUri = data == null || resultCode != RESULT_OK ? null : data.getData();
        }

        if (resultUri == null) {
            ToastUtils.show("读取图片出错");
            return;
        }
        showProgress();

        ThreadPoolManager.getInstance().execute(() -> {
            try {
                tmpBitmap = ImageUtil.compressBitmapFormUri(mContext, resultUri, 80);
                hander.sendEmptyMessage(1);

            } catch (Exception e) {
                hideProgress();
                e.printStackTrace();
            }
            if (tmpBitmap != null) {
                String base64Url = "data:image/png;base64,"+ImageUtil.bitmapToBase64NONseal(tmpBitmap);
                if (isFront){
                    front_name= RandomUntil.getNum(100000,1000000)+".png";
                    front_uri_str=base64Url;
                    IDCardRequest request=new IDCardRequest();
                    IDCardRequest.IDCard idCard=request.new IDCard();
                    idCard.setFile(front_uri_str);
                    idCard.setFileName(front_name);
                    idCard.setFileType(10100);
                    map.put("0",idCard);

                }else{
                    back_name=RandomUntil.getNum(100000,1000000)+".png";
                    back_uri_str=base64Url;
                    IDCardRequest request=new IDCardRequest();
                    IDCardRequest.IDCard idCard=request.new IDCard();
                    idCard.setFile(back_uri_str);
                    idCard.setFileName(back_name);
                    idCard.setFileType(10101);
                    map.put("1",idCard);
                }

                checkButtonState();


            }
        });
    }

    public void checkButtonState(){
        hander.sendEmptyMessage(2);

    }

}
